<template>
  <div class="echarts-box">
    <a-form class="smart-query-form">
      <a-row class="smart-query-form-row">
        <a-form-item label="通行时间" class="smart-query-form-item">
          <a-range-picker :format="format" v-model:value="queryForm.times" show-time />
        </a-form-item>
        <a-form-item label="时间刻度" class="smart-query-form-item">
          <div class="query-form-button-list">
            <a-space>
              <a-button
                v-for="item in timeList"
                :key="item.value"
                @click="dateTypeChange(item)"
                :type="queryForm.dateType === item.value ? 'primary' : 'default'"
              >
                {{ item.name }}
              </a-button>
            </a-space>
          </div>
        </a-form-item>
        <a-form-item label="事件区域" class="smart-query-form-item">
          <a-select ref="select" v-model:value="queryForm.areaId" style="width: 175px" placeholder="请选择事件区域" allowClear>
            <a-select-option v-for="item in areaList" :key="item.areaId" :value="item.areaId">
              {{ item.areaName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item class="smart-query-form-item query-button">
          <a-space>
            <a-button @click="queryData">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="showChart" class="smart-margin-left11">
              <template #icon>
                <AreaChartOutlined />
              </template>
              表格
            </a-button>
          </a-space>
        </a-form-item>
      </a-row>
    </a-form>
    <div class="gradient-main" id="gradient-main"></div>
  </div>
</template>
<script setup>
  import { ref } from 'vue';
  import * as echarts from 'echarts';
  import { onMounted } from 'vue';
  import { dateFormat } from '/@/utils/date';
  import dayjs from 'dayjs';
  import { api } from '/@/api/plat/event.js';
  import { api as areaApi } from '/@/api/plat/area.js';

  const timeList = [
    {
      name: '年',
      value: '0',
    },
    {
      name: '月',
      value: '1',
    },
    {
      name: '周',
      value: '2',
    },
    {
      name: '日',
      value: '3',
    },
  ];
  const emit = defineEmits(['change']);
  const format = 'YYYY-MM-DD HH:mm:ss';
  const initDate = () => {
    const startTime = dateFormat(new Date(+new Date() - 365 * 24 * 60 * 60 * 1000));
    const endTime = dateFormat();
    return [dayjs(startTime, format), dayjs(endTime, format)];
  };
  const queryFormState = {
    dateType: '1',
    times: initDate(),
  };
  let areaList = ref([]);
  const queryForm = ref({ ...queryFormState });

  onMounted(() => {
    getAreaList();
  });

  function getAreaList() {
    areaApi.queryList().then(({ data }) => {
      areaList.value = data;
      // queryForm.value.areaId = data[0]?.areaId;
      queryData();
    });
  }

  function queryData() {
    if (queryForm.value.times && queryForm.value.times.length > 0) {
      queryForm.value.startTime = dateFormat(queryForm.value.times[0]);
      queryForm.value.endTime = dateFormat(queryForm.value.times[1]);
    }
    onload();
  }

  function onload() {
    let formData = { ...queryForm.value };
    delete formData.times;
    formData.limit = getTimeInterval(formData);
    api.queryStat(formData).then(({ data }) => {
      init(data.reverse());
    });
  }

  function getTimeInterval(row) {
    const { startTime, endTime, dateType } = row;
    const start = new Date(startTime);
    const end = new Date(endTime);

    let limit = 0;

    // 根据dateType的值计算不同的时间间隔
    switch (dateType) {
      case '0': // 年
        limit = end.getFullYear() - start.getFullYear();
        break;
      case '1': // 月
        limit = (end.getFullYear() - start.getFullYear()) * 12 + end.getMonth() - start.getMonth();
        break;
      case '2': // 周
        const oneWeek = 1000 * 60 * 60 * 24 * 7; // 一周的毫秒数
        const timeDiff = end - start; // 时间差
        limit = Math.floor(timeDiff / oneWeek);
        break;
      case '3': // 日
        const oneDay = 1000 * 60 * 60 * 24; // 一天的毫秒数
        const dayDiff = end - start;
        limit = Math.floor(dayDiff / oneDay);
        break;
      default:
        throw new Error('Invalid dateType');
    }

    return limit;
  }

  function init(data) {
    let option = {
      color: ['#80FFA5', '#00DDFF', '#37A2FF', '#FF0087', '#FFBF00'],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985',
          },
        },
      },
      grid: [
        {
          top: '10%',
          left: '3%',
          right: '4%',
          height: '40%',
          containLabel: true,
        },
        {
          top: '60%',
          left: '3%',
          right: '4%',
          height: '40%',
          containLabel: true,
        },
      ],
      xAxis: [
        {
          type: 'category',
          gridIndex: 0,
          axisLabel: {
            textStyle: {
              color: '#fff',
            },
          },
          data: data.map((m) => m.dateStr),
        },
        {
          type: 'category',
          gridIndex: 1,
          axisLabel: {
            textStyle: {
              color: '#fff',
            },
          },
          data: data.map((m) => m.dateStr),
        },
      ],
      yAxis: [
        {
          type: 'value',
          gridIndex: 0,
          axisLabel: {
            textStyle: {
              color: '#fff',
            },
          },
        },
        {
          // 下层柱状图的Y轴
          type: 'value',
          gridIndex: 1,
          axisLabel: {
            textStyle: {
              color: '#fff',
            },
          },
        },
      ],
      series: [
        {
          name: '事件',
          type: 'line',
          stack: 'Total',
          smooth: true,
          lineStyle: {
            width: 0,
          },
          showSymbol: false,
          areaStyle: {
            opacity: 0.8,
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgb(128, 255, 165)',
              },
              {
                offset: 1,
                color: 'rgb(1, 191, 236)',
              },
            ]),
          },
          emphasis: {
            focus: 'series',
          },
          data: data.map((m) => m.total),
          xAxisIndex: 0,
          yAxisIndex: 0,
        },
        {
          name: '事件',
          type: 'bar',
          data: data.map((m) => m.total),
          xAxisIndex: 1,
          yAxisIndex: 1,
        },
      ],
    };
    let chartDom = document.getElementById('gradient-main');
    if (chartDom) {
      let myChart = echarts.init(chartDom);
      option && myChart.setOption(option);
    }
  }

  function resetQuery() {
    queryForm.value = { ...queryFormState };
    queryData();
  }

  function showChart() {
    emit('change', 'TableCard');
  }

  function dateTypeChange(row) {
    queryForm.value.dateType = row.value;
    onload();
  }
</script>
<style lang="less" scoped>
  .echarts-box {
    width: 100%;
    height: 100%;
    .smart-query-form {
      background-color: transparent;
      &:deep .ant-form-row {
        .ant-form-item-label {
          label {
            color: #fff;
          }
        }
        input::placeholder {
          font-size: 14px;
        }
      }
    }
    .gradient-main {
      width: 100%;
      height: calc(100vh - 200px);
    }
  }
  .query-button {
    margin-left: 30px;
  }
  .smart-margin-left11 {
    background-color: #e6a23c;
    border-color: #e6a23c;
    color: #fff;
    &:hover {
      background-color: #ebb563;
      color: #fff;
      border-color: #e6a23c;
    }
  }
</style>
